<template>
  <el-drawer
    :title="copName"
    size="1000px"
    :visible.sync="isShowDrawer"
    @close="closeDrawer"
  >
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        label-width="auto"
        label-suffix="："
        :rules="rules"
      >
        <div class="property-title">{{ $t('message.tcsx') }}</div>
        <el-form-item :label="$t('message.tcname')" prop="name">
          <el-input
            v-model="param.name"
            class="w400"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.tcname')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.lx')" class="select-style" prop="mealsType">
          <el-select
            v-model="param.mealsType"
            :disabled="id != ''"
            class="w400"
            :placeholder="$t('message.csk')"
            @change="changeType"
          >
            <el-option
              v-for="item in mealsTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <template v-if="param.mealsType == '1'">
          <el-form-item :label="$t('message.mrcrxz')">
            <el-radio
              v-model="limitNumFlag"
              label="0"
              @change="changeinOutNum"
            >{{ $t('message.bxz') }}</el-radio>
            <el-radio
              v-model="limitNumFlag"
              label="1"
              @change="changeinOutNum"
            >{{ $t('message.xzcs') }}</el-radio>
            <el-input
              v-if="limitNumFlag === '1'"
              v-model="param.inOutNum"
              :maxlength="5"
              class="w100"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            />
            <span v-if="limitNumFlag === '1'" class="mll0"> {{ $t('message.ci') }}</span>
          </el-form-item>
        </template>
        <template v-if="param.mealsType == '4'">
          <el-form-item :label="$t('message.mrykxz')">
            <el-radio
              v-model="limitNumFlag"
              label="0"
              @change="changeinOutNum"
            >{{ $t('message.bxz') }}</el-radio>
            <el-radio
              v-model="limitNumFlag"
              label="1"
              @change="changeinOutNum"
            >{{ $t('message.xzcs') }}</el-radio>
            <el-input
              v-if="limitNumFlag === '1'"
              v-model="param.inOutNum"
              :maxlength="5"
              class="w100"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            />
            <span v-if="limitNumFlag === '1'" class="mll0"> {{ $t('message.ci') }}</span>
          </el-form-item>
        </template>
        <div
          v-if="
            param.mealsType == '0' ||
              param.mealsType == '2' ||
              param.mealsType == '3'
          "
        >
          <el-form-item :label="$t('message.tccs')" prop="nums">
            <el-input
              v-model="param.nums"
              maxlength="4"
              class="w400"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              :placeholder="$t('message.qsr') + $t('message.cs')"
            />
          </el-form-item>
        </div>
        <div
          v-if="
            param.mealsType == '0' ||
              param.mealsType == '2' ||
              param.mealsType == '3'
          "
        >
          <el-form-item :label="$t('message.zscs')" prop="giveNums">
            <el-input
              v-model="param.giveNums"
              class="w400"
              maxlength="10"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^0-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              :placeholder="$t('message.qsr') + $t('message.zscs')"
            />
          </el-form-item>
        </div>
        <el-form-item :label="$t('message.jgy')" prop="price">
          <el-input
            v-model="param.price"
            class="w400"
            maxlength="10"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            :placeholder="$t('message.qsr') + $t('message.price')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.xsqd')" prop="channel">
          <el-checkbox-group v-model="param.channel">
            <el-checkbox
              v-for="(item, index) in channels"
              :key="index"
              :label="item.value"
              :value="item.value"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('message.sfxg')" prop="isXg">
          <el-radio-group v-model="param.isXg">
            <el-radio label="0">{{ $t('message.bxg') }}</el-radio>
            <el-radio label="1">{{ $t('message.xgsl') }}</el-radio>
          </el-radio-group>
          <el-input
            v-if="param.isXg== 1"
            v-model="param.memberLimit"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            maxlength="10"
            class="w200 ml10"
          >
            <template #append>{{ $t('message.fen') }}</template>
          </el-input>
          <span class="placeholder6 ml20">{{ $t('message.xzdghygmdsl') }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.zr')" prop="transferValue">
          <el-input v-if="param.transferValueType == '2'" v-model="param.transferValue" class="w400" maxlength="10" :placeholder="$t('message.qsr') + $t('message.zrfy')" clearable oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=null">
            <template #append>
              <el-select v-model="param.transferValueType" style="width: 70px;" @change="$set(param, 'transferValue', '')">
                <el-option
                  v-for="(item, index) in sxflxList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >{{ item.label }} </el-option>
              </el-select>
            </template>
          </el-input>
          <el-input v-if="param.transferValueType == '1'" v-model="param.transferValue" class="w400" maxlength="10" :placeholder="$t('message.qsr') + $t('message.zrfy')" clearable onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}">
            <template #append>
              <el-select v-model="param.transferValueType" style="width: 70px;" @change="$set(param, 'transferValue', '')">
                <el-option
                  v-for="(item, index) in sxflxList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >{{ item.label }} </el-option>
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('message.dj')" prop="freezeValueType">
          <el-input v-if="param.freezeValueType == '2'" v-model="param.freezeValue" class="w400" maxlength="10" :placeholder="$t('message.qsr') + $t('message.djfy')" clearable oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=null">
            <template #append>
              <el-select v-model="param.freezeValueType" style="width: 70px;" @change="$set(param, 'freezeValue', '')">
                <el-option
                  v-for="(item, index) in sxflxList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >{{ item.label }} </el-option>
              </el-select>
            </template>
          </el-input>
          <el-input v-if="param.freezeValueType == '1'" v-model="param.freezeValue" class="w400" maxlength="10" :placeholder="$t('message.qsr') + $t('message.djfy')" clearable onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}">
            <template #append>
              <el-select v-model="param.freezeValueType" style="width: 70px;" @change="$set(param, 'freezeValue', '')">
                <el-option
                  v-for="(item, index) in sxflxList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >{{ item.label }} </el-option>
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('message.tctp')" class="select-style">
          <el-radio-group v-model="param.imgType" @change="changeImgType">
            <el-radio
              v-for="(item, index) in defaultImgs"
              :key="index"
              :label="item.code"
            >{{ item.remaks }}</el-radio>
          </el-radio-group>
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="MEALS_IMG"
              :fixed-number="[690, 388]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="upload-wrap df_ac">
            <el-upload
              v-if="param.imgType == 'mealsImgZero'"
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              accept=".jpg,.png,.jpeg"
              :auto-upload="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-if="!param.showUrl"
                style="color: #999999; font-size: 14px; line-height: 20px"
              >
                {{ $t('message.sctp') }}
              </div>
              <div
                v-show="param.showUrl"
                class="file"
                :style="'background-image: url(' + param.showUrl + ')'"
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage"
                  />
                </div>
              </div>
            </el-upload>
            <div
              v-if="param.imgType == 'mealsImgZero'"
              class="placeholader tip-style"
            >
              <div class="placeholder9">{{ $t('message.jycc') }}：690px * 334px;</div>
              <div>
                {{ $t('message.zctpsm') }}
              </div>
            </div>
          </div>
          <img
            v-if="param.imgType != 'mealsImgZero' && param.showUrl"
            style="width: 174px; height: 84px"
            :src="param.showUrl"
          >
        </el-form-item>

        <el-form-item :label="$t('message.miaoshu')">
          <el-input
            v-model="param.content"
            :autosize="{ minRows: 3 }"
            class="w400"
            maxlength="200"
            type="textarea"
            :placeholder="$t('message.qsr')"
          />
        </el-form-item>

        <div class="mb20">
          <span class="property-title">{{ $t('message.sjsz') }}</span>
          <span class="sub-title">{{ $t('message.xssjsysjsz') }}</span>
        </div>
        <el-form-item :label="$t('message.xssd')" prop="timeSale">
          <el-date-picker
            v-model="param.timeSale"
            type="datetimerange"
            range-separator="~"
            :start-placeholder="$t('message.ksrq')"
            :end-placeholder="$t('message.jsrq')"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>
        <div class="df">
          <el-form-item
            :label="$t('message.sysj')"
            class="select-style"
            prop="validityType"
          >
            <el-select
              v-model="param.validityType"
              class="w200 mr20"
              :placeholder="$t('message.qxz') + $t('message.sysj')"
            >
              <el-option :label="$t('message.gdrq')" value="0" />
              <el-option :label="$t('message.gmhsx')" value="1" />
              <el-option :label="$t('message.zdrqsx')" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="param.validityType === '0'"
            label-width="0"
            prop="validityTime"
          >
            <span>{{ $t('message.gdrq') }}：</span>
            <el-date-picker
              v-model="param.validityTime"
              type="daterange"
              class="w400"
              :range-separator="$t('message.zhi')"
              :start-placeholder="$t('message.ksrq')"
              :end-placeholder="$t('message.jsrq')"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item
            v-if="param.validityType === '2'"
            label-width="0"
            prop="assignValidTime"
          >
            <el-date-picker
              v-model="param.assignValidTime"
              type="date"
              class="w200"
              :picker-options="pickerOptionsb"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
            <span class="mr10" style="margin-left: 10px;">{{ $t('message.kssx') }}</span>
          </el-form-item>
          <el-form-item
            v-if="param.validityType === '1' || param.validityType === '2'"
            label-width="0"
            prop="indate"
          >
            <span>{{ $t('message.yxq') }}：</span>
            <el-input
              v-model="param.indate"
              class="w200 mr10"
              onkeyup="value=value.replace(/[^\d^]/g,'')"
              oninput="if(value<=0) { value = ''}"
              :placeholder="$t('message.qsr') + $t('message.yxts')"
            />
            <span>{{ $t('message.tian') }}</span>
          </el-form-item>
        </div>
        <el-form-item :label="$t('message.sjdxz')" prop="timer">
          <el-radio
            v-model="param.rulesTimeSectionFlag"
            label="1"
            @change="changeTimes"
          >{{ $t('message.qsdky') }}</el-radio>
          <el-radio
            v-model="param.rulesTimeSectionFlag"
            label="0"
            @change="changeTimes"
          >{{ $t('message.zdsdky') }}</el-radio>
          <div v-if="param.rulesTimeSectionFlag == '0'">
            <el-checkbox-group v-model="selWeekList" class="mb10">
              <el-checkbox
                v-for="item in weekList"
                :key="item.value"
                :label="item.value"
              >{{ item.label }}</el-checkbox>
            </el-checkbox-group>
            <div class="df">
              <span class="mr10">{{ $t('message.meir') }}</span>
              <div>
                <el-time-picker
                  v-model="param.useTime"
                  is-range
                  class="w200 mr10"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="~"
                  :start-placeholder="$t('message.kssj')"
                  :end-placeholder="$t('message.jssj')"
                  :placeholder="$t('message.xzsjfw')"
                />
              </div>
              <span>{{ $t('message.keyon') }}</span>
            </div>
          </div>
        </el-form-item>

        <div class="property-title">{{ $t('message.hyzk') }}</div>
        <el-form-item :label="$t('message.zklx')" class="select-style">
          <div class="df_ac">
            <el-select
              v-model="param.discountType"
              :placeholder="$t('message.qxz') + $t('message.zklx')"
              class="w400"
            >
              <el-option
                v-for="item in discountTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span
              v-if="param.discountType && param.discountType == '1'"
              class="placeholder9 ml10"
            >{{ $t('message.ldsywxs') }}</span>
          </div>
        </el-form-item>
        <el-form-item
          v-if="param.discountType === '1'"
          label-width="0"
          class="select-style"
        >
          <el-form-item
            v-for="(item, index) in param.vipTypes"
            :key="index"
            :label="item.name"
            :prop="`vipTypes[${index}].value`"
            :rules="{ required: true, message: $t('message.qsr') + $t('message.zhekou'), trigger: 'blur' }"
            class="count-style"
          >
            <el-input
              v-model="item.value"
              class="input-style"
              maxlength="3"
              onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{1,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
              oninput="if(value<0||value>10) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{1,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
              :placeholder="$t('message.qsr') + $t('message.zhekou')"
            />
          </el-form-item>
        </el-form-item>

        <div class="property-title">{{ $t('message.sygz') }}</div>
        <el-form-item :label="$t('message.zffsl')" prop="circulationAll">
          <el-input
            v-model="param.circulationAll"
            class="w200 mr10"
            maxlength="10"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            :placeholder="$t('message.qsr') + $t('message.zffsl')"
          />
          <span class="placeholder9 ml10">
            {{ $t('message.zffslsm') }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.rffsl')" prop="circulationDay">
          <el-input
            v-model="param.circulationDay"
            class="w200 mr10"
            maxlength="10"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            :placeholder="$t('message.qsr') + $t('message.rffsl')"
          />
          <span class="placeholder9 ml10">{{ $t('message.rffslsm') }}</span>
        </el-form-item>
        <el-form-item
          v-if="param.mealsType == '2'"
          :label="$t('message.zcbcqc')"
          prop="useSiteFullType"
        >
          <el-radio
            v-model="param.useSiteFullType"
            label="0"
            @change="changeItems"
          >{{ $t('message.quanchan') }}</el-radio>
          <el-radio
            v-model="param.useSiteFullType"
            label="1"
            @change="changeItems"
          >{{ $t('message.banchan') }}</el-radio>
          <span class="placeholder9 ml10">{{ $t('message.gxmzcbchqc') }}</span>
        </el-form-item>
        <el-form-item
          v-if="
            param.rulesVenueFlag === '0' &&
              param.mealsType != '3' &&
              param.mealsType != '4'
          "
          :label="$t('message.syxm')"
        >
          <el-radio
            v-model="param.rulesProjectFlag"
            label="1"
            @change="changeItems"
          >{{ $t('message.qbxmky') }}</el-radio>
          <el-radio
            v-model="param.rulesProjectFlag"
            label="0"
            @change="changeItems"
          >{{ $t('message.zdxmky') }}</el-radio>
          <el-table
            v-if="param.rulesProjectFlag == '0'"
            :data="venueProjectListDataForTable"
            border
          >
            <el-table-column prop="name" :label="$t('message.cg')" width="200px" />
            <el-table-column :label="$t('message.xm')">
              <template slot-scope="scope">
                <el-checkbox-group v-model="checkedItems">
                  <el-checkbox
                    v-for="(item, index) in scope.row.projects"
                    :key="index"
                    :label="item.id"
                    :disabled="venueId != scope.row.id"
                    @change="checkProject()"
                  >{{ item.projectName }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item
          v-if="param.mealsType === '3' || param.mealsType === '4'"
          :label="$t('message.kykcxz')"
        >
          <el-radio
            v-model="param.rulesCourseFlag"
            label="1"
            @change="changeItems"
          >{{ $t('message.qbkc') }}</el-radio>
          <el-radio
            v-model="param.rulesCourseFlag"
            label="0"
            @change="changeItems"
          >{{ $t('message.zdkc') }}</el-radio>
          <div v-if="param.rulesCourseFlag == '0'">
            <div class="venue-list">
              <el-checkbox-group v-model="checkedCourse">
                <el-checkbox
                  v-for="item in courseList"
                  :key="item.courseId"
                  :label="item.courseId"
                >{{ item.courseName }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          v-if="param.mealsType === '3' || param.mealsType === '4'"
          :label="$t('message.kyjlxz')"
        >
          <el-radio
            v-model="param.rulesTeacherFlag"
            label="1"
            @change="changeItems"
          >{{ $t('message.qbjl') }}</el-radio>
          <el-radio
            v-model="param.rulesTeacherFlag"
            label="0"
            @change="changeItems"
          >{{ $t('message.zdjl') }}</el-radio>
          <div v-if="param.rulesTeacherFlag == '0'">
            <div class="venue-list">
              <el-checkbox-group v-model="checkedTeacher">
                <el-checkbox
                  v-for="item in teacherLevels"
                  :key="item.id"
                  :label="item.id"
                >{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>
        <div class="separate" />
        <el-button
          v-preventReClick
          type="primary"
          :loading="submitLoading"
          @click="formOnSubmit('form')"
        >{{ $t('message.tj') }}</el-button>
        <el-button @click="closeDrawer">{{ $t('message.qx') }}</el-button>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import {
  editOrAddMeal,
  venueProjectList,
  mealInfob,
  uploadFile,
  cardList,
  teacherLevelPost,
  courseListPost,
  defaultImage
} from '@/api'
import { rules, mealsTypes, weekList } from './config'
import { pickerOptionsS, pickerOptionsDis } from '@/utils/config'
import Cropper from '@/components/cropper'
export default {
  name: 'ComboAdd',
  components: {
    Cropper
  },
  data() {
    return {
      weekList,
      venueId: sessionStorage.getItem('venueId'),
      sxflxList: [
        {
          label: this.$t('message.yuan'),
          value: '1'
        },
        {
          label: '%',
          value: '2'
        }],
      id: '',
      isShowDrawer: false,
      submitLoading: false,
      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      pickerOptions: pickerOptionsS,
      pickerOptionsb: pickerOptionsDis,
      discountTypeList: [
        {
          value: '0',
          label: this.$t('message.mrzk')
        },
        {
          value: '1',
          label: this.$t('message.zdyzk')
        }
      ],
      channels: [
        { value: '1', name: this.$t('message.xcx') },
        { value: '2', name: this.$t('message.cgd') }
      ],
      copName: this.$t('message.xztc'),
      imageList: [],
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'MEALS_IMG'
      },
      limitNumFlag: '0',
      filters: {},
      mealsTypes,
      selWeekList: [],
      venueProjectListData: [],
      venueProjectListDataForTable: [],
      projectCheckList: [],
      checkedItems: [],
      checkedCourse: [],
      checkedTeacher: [],
      defaultImgs: [],
      param: {
        rulesVenueFlag: '1',
        rulesProjectFlag: '1',
        useSiteFullType: '0',
        rulesTimeSectionFlag: '1',
        rulesTeacherFlag: '1',
        rulesCourseFlag: '1',
        inOutNum: -1,
        validityType: '0',
        isXg: '0',
        memberLimit: '',
        transferValueType: '1',
        freezeValueType: '1',
        nums: '',
        giveNums: '',
        indate: '',
        circulationDay: '', // 发行数量
        name: '', // 套餐名称
        mealsType: '0', // 套餐类型（0次数卡1期限卡
        content: '', // 描述
        imgurl: '',
        showUrl: '',
        insertUrl: '',
        price: '',
        discountType: '0',
        discountMap: {},
        saleDateStart: '',
        saleDateEnd: '',
        timeSale: [],
        checkedVenue: [],
        vipTypes: [],
        channel: ['2'],
        mealsRules: {
          // 使用规则
          useStadiums: '', // 适用场馆
          useItems: '' // 适用项目
        }
      },
      rules,
      teacherLevels: [],
      courseList: []
    }
  },
  created() {
    this.getVenueProjectList()
    this.getCardList()
    setTimeout(() => {
      this.getDefaultImage()
    }, 1000)
  },
  methods: {
    onSubmit() {
      const that = this
      const param = { ...this.param }
      if (param.circulationAll && param.circulationAll !== '0') {
        if (param.circulationAll * 1 < param.circulationDay * 1) {
          return this.$message.warning(this.$t('message.zfxslxdyrfxsl'))
        }
      }
      if (this.selWeekList.length) {
        param.mealsRules.useDays = this.selWeekList.join(',')
      }
      if (param.isXg && param.isXg === '1') {
        if (!param.memberLimit) {
          return this.$message.warning(this.$t('message.qsr') + this.$t('message.xgsl'))
        }
      }
      param.saleDateStart = this.param.timeSale[0]
      param.saleDateEnd = this.param.timeSale[1]
      if (this.param.validityType === '0') {
        param.validityStartTime = this.param.validityTime[0]
        param.validityEndTime = this.param.validityTime[1]
        if (new Date(param.saleDateEnd).getTime() >= new Date(param.validityEndTime + ' 23:59:59').getTime()) {
          this.param.validityTime = null
          return this.$message.warning(this.$t('message.xssjbkszzsysjzh'))
        }
      } else {
        param.indate = parseInt(this.param.indate)
      }
      if (param.useTime) {
        param.mealsRules.useTimeStart = param.useTime[0]
        param.mealsRules.useTimeEnd = param.useTime[1]
      }
      if (param.circulationAll === '') {
        param.circulationAll = -1
      }
      if (param.discountType === '1') {
        const discounts = {}
        for (const dc of param.vipTypes) {
          discounts[dc.id] = dc.value * 0.1.toFixed(1)
        }
        param.discountMap = discounts
      }

      if (param.inOutNum) {
        param.inOutNum = param.inOutNum * 1
      }
      if (param.checkedVenue.length) {
        param.mealsRules.useStadiums = param.checkedVenue.join(',')
      }
      if (this.checkedItems.length) {
        param.mealsRules.useItems = this.checkedItems.join(',')
      }
      param.channel = this.param.channel.length > 1 ? this.param.channel.join(',') : this.param.channel[0]
      param.id = this.id ? this.id : null
      if (this.checkedCourse.length > 0 && param.rulesCourseFlag === '0') {
        param.mealsRules.useCourse = this.checkedCourse.join(',')
      } else {
        param.mealsRules.useCourse = ''
      }
      if (this.checkedTeacher.length > 0 && param.rulesTeacherFlag === '0') {
        param.mealsRules.useTeacherLevel = this.checkedTeacher.join(',')
      } else {
        param.mealsRules.useTeacherLevel = ''
      }
      param.mealsRules.useSiteFullType = param.useSiteFullType
      console.log(param)

      that.submitLoading = true
      editOrAddMeal({ param, userId: sessionStorage.getItem('userId') })
        .then((res) => {
          // console.log(res)
          that.submitLoading = false
          if (res.errorCode !== '000000') return
          if (res.errorCode === '000000') {
            if (this.id) {
              this.$message.success(this.$t('message.editcg'))
              this.isShowDrawer = false
              this.$emit('success')
            } else {
              this.$message.success(this.$t('message.addcg'))
              this.isShowDrawer = false
              this.$emit('success')
            }
          }
        })
        .catch((er) => {
          that.submitLoading = false
          console.log(er)
        })
    },
    changeinOutNum(val) {
      if (val === '0') {
        this.$set(this.param, 'inOutNum', -1)
      } else {
        this.$set(this.param, 'inOutNum', 1)
      }
    },
    initCourseConfig() {
      teacherLevelPost({
        param: {
          venueIds: this.param.checkedVenue || []
        }
      }).then(res => {
        this.teacherLevels = res.recordList || []
      })
      courseListPost({
        param: {
          courseType: '4',
          payType: '01',
          venueIds: this.param.checkedVenue || []
        }
      }).then(res => {
        this.courseList = res.recordList || []
      })
    },
    changeImgType(e) {
      console.log(e)
      if (e === 'mealsImgZero') {
        this.$set(this.param, 'insertUrl', '')
        this.$set(this.param, 'showUrl', '')
        this.$set(this.param, 'imgurl', '')
      } else {
        const arr = this.defaultImgs
        arr.forEach(s => {
          if (s.code === e) {
            this.$set(this.param, 'insertUrl', s.pic)
            this.$set(this.param, 'showUrl', s.showPic)
            this.$set(this.param, 'imgurl', s.pic)
            console.log(this.param)
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    getDefaultImage() {
      defaultImage({ param: { type: '8' }}).then(res => {
        this.defaultImgs = res.record
        if (!this.param.id && this.defaultImgs.length > 0) {
          console.log('this.param', this.param)
          this.$set(this.param, 'imgType', res.record[0].code)
          this.$set(this.param, 'insertUrl', res.record[0].pic)
          this.$set(this.param, 'showUrl', res.record[0].showPic)
          this.$nextTick(() => {
            // this.$refs.form.clearValidate()
          })
        }
      })
    },
    changeTimes() {
      this.$set(this.param, 'useDays', null)
      this.$set(this.param, 'useTime', null)
      this.selWeekList = []
    },
    formOnSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.onSubmit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    changeType(val) {
      if (val === '3' || val === '4') {
        this.initCourseConfig()
      }
      this.limitNumFlag = '0'
      this.param = {
        rulesVenueFlag: '0',
        freezeValueType: '1',
        isXg: '0',
        memberLimit: '',
        transferValueType: '1',
        rulesProjectFlag: '1',
        useSiteFullType: '0',
        rulesTimeSectionFlag: '1',
        rulesTeacherFlag: '1',
        rulesCourseFlag: '1',
        inOutNum: -1,
        validityType: '0',

        nums: '',
        giveNums: '',
        indate: '',
        circulationDay: '', // 发行数量
        name: '', // 套餐名称
        mealsType: val, // 套餐类型（0次数卡1期限卡
        content: '', // 描述
        imgurl: '',
        showUrl: '',
        insertUrl: '',
        price: '',
        discountType: '0',
        discountMap: {},
        saleDateStart: '',
        saleDateEnd: '',
        timeSale: [],
        checkedVenue: [sessionStorage.getItem('venueId')],
        vipTypes: [],
        channel: ['2'],
        mealsRules: {
          // 使用规则
          useStadiums: '', // 适用场馆
          useItems: '' // 适用项目
        }
      }
      this.getCardList()
    },
    changeVenue(val) {
      this.param.checkedVenue = []
      if (val === '0') {
        this.venueProjectListDataForTable = []
      } else {
        this.venueProjectListDataForTable = this.venueProjectListData
      }
      console.log(this.param.checkedVenue)
      this.changeItems()
    },
    changeItems() {
      this.checkedItems = []
      this.param.mealsRules.useItems = ''
    },
    closeDrawer() {
      this.isShowDrawer = false
      this.$emit('close')
    },
    getCardList() {
      // 获取卡类型列表
      cardList({
        pagination: {
          page: 1,
          rows: 1000,
          firstQueryTime: this.firstQueryTime
        },
        param: {
          cardName: null,
          isnormal: null,
          channel: null,
          type: '1'
        }
      }).then(res => {
        // console.log(res)
        if (res.errorCode === '000000') {
          // eslint-disable-next-line no-unused-vars
          for (const item of res.recordList) {
            if (item.status === '1') {
              this.param.vipTypes.push({ name: item.cardName, id: item.id, value: null })
            }
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 上传成功
    uploadSuccess(response, file, fileList) {
      console.log(fileList[0].response.insertUrl)
      console.log(this.imageList)
      this.param.imgurl = fileList[0].response.insertUrl
      this.$refs.form.clearValidate()
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showUrl', config.showUrl)
        this.$set(this.param, 'insertUrl', config.insertUrl)
        this.param.imgurl = config.insertUrl
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    deleteDeviceConfigAddImage() {
      this.param.showUrl = ''
      this.param.insertUrl = ''
      this.$set(this.param, 'imgurl', '')
    },
    // 获取场馆项目
    getVenueProjectList() {
      venueProjectList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueProjectListData = res.recordList
        this.venueProjectListDataForTable = res.recordList || []
        if (!this.id) {
          const param = { ...this.param }
          param.checkedVenue = [sessionStorage.getItem('venueId')]
          this.param = {
            ...param, isXg: '0'
          }
          this.checkVenue()
        }
      })
    },
    // 重置场馆项目选中状态
    resetVenueProject() {
      const { venueProjectListData, checkedVenue } = this
      const checedList = []
      if (checkedVenue.length === 0) {
        this.venueProjectListDataForTable = venueProjectListData
      } else {
        for (const i in venueProjectListData) {
          for (const j in checkedVenue) {
            if (venueProjectListData[i].id === checkedVenue[j]) {
              checedList.push(venueProjectListData[i])
            }
          }
        }
        this.venueProjectListDataForTable = checedList
      }
    },
    // 选择场馆
    checkVenue(e) {
      const { venueProjectListData, param } = this
      const checedList = []
      for (const i in venueProjectListData) {
        if (e.includes(venueProjectListData[i].id)) {
          checedList.push(venueProjectListData[i])
        }
      }
      this.venueProjectListDataForTable = checedList
      if (param.mealsType === '3' || param.mealsType === '4') {
        this.initCourseConfig()
        // this.checkedCourse = []
        // this.checkedTeacher = []
      }
    },
    // 选择项目
    checkProject(e) {
      console.log(e, this.checkedItems)
    },
    // 获取套餐详情
    getMealInfo(id) {
      Promise.all(
        [
          mealInfob({
            param: { id },
            userId: sessionStorage.getItem('userId')
          }),
          cardList({
            pagination: {
              page: 1,
              rows: 1000,
              firstQueryTime: this.firstQueryTime
            },
            param: {
              cardName: null,
              isnormal: null,
              channel: null,
              type: '1'
            }
          })
        ]
      )
        .then((res) => {
          const combo = res[0].record
          this.getVenueProjectList()
          this.imageList.push({
            url: combo.fullImgurl,
            response: {
              insertUrl: combo.imgurl,
              showUrl: combo.fullImgurl
            }
          })

          this.$set(this.param, 'imgType', combo.imgType || 'mealsImgZero')
          this.$set(this.param, 'showUrl', combo.fullImgurl)
          this.$set(this.param, 'insertUrl', combo.imgurl)
          this.param.id = combo.id
          this.param.nums = combo.nums
          // this.param.circulationAll = combo.circulationAll
          this.$set(this.param, 'circulationAll', combo.circulationAll)
          this.$set(this.param, 'circulationDay', combo.circulationDay)
          if (combo.inOutNum) {
            this.param.inOutNum = combo.inOutNum
            this.limitNumFlag = '1'
          }
          this.param.rulesVenueFlag = combo.rulesVenueFlag
          this.param.rulesProjectFlag = combo.rulesProjectFlag

          this.param.giveNums = combo.giveNums
          this.param.name = combo.name
          this.param.indate = combo.indate
          this.param.mealsType = combo.mealsType
          this.param.content = combo.content
          this.param.imgurl = combo.imgurl
          this.param.price = combo.price
          this.param.insertUrl = combo.imgurl
          this.param.showUrl = combo.fullImgurl
          this.param.channel = combo.channel.split(',')
          this.param.discountType = combo.discountType
          this.param.saleDateStart = combo.saleDateStart
          this.param.saleDateEnd = combo.saleDateEnd
          this.$set(this.param, 'useSiteFullType', combo.useSiteFullType || '0')
          this.$set(this.param, 'assignValidTime', combo.assignValidTime || '')
          this.$set(this.param, 'transferValue', combo.transferValue || '')
          this.$set(this.param, 'transferValueType', combo.transferValueType || '1')
          this.$set(this.param, 'freezeValue', combo.freezeValue || '')
          this.$set(this.param, 'freezeValueType', combo.freezeValueType || '1')
          this.$set(this.param, 'isXg', combo.isXg || '0')
          this.$set(this.param, 'memberLimit', combo.memberLimit || '')
          if (combo.saleDateStart) {
            const timeSale = [combo.saleDateStart, combo.saleDateEnd]
            this.param.timeSale = timeSale
          }
          this.param.checkedVenue = combo.useStadiums || []
          this.checkedItems = combo.useItems || []
          this.param.vipTypes = []
          if (combo.validityStartTime && combo.validityEndTime) {
            this.$set(this.param, 'validityTime', [combo.validityStartTime, combo.validityEndTime])
          } else {
            this.$set(this.param, 'validityTime', [])
          }
          this.$set(this.param, 'rulesTimeSectionFlag', combo.rulesTimeSectionFlag)
          this.$set(this.param, 'validityType', combo.validityType)
          if (combo.useTimeStart || combo.useTimeEnd) {
            this.$set(this.param, 'useTime', [combo.useTimeStart, combo.useTimeEnd])
          }
          if (combo.useDays) {
            this.selWeekList = combo.useDays.includes(',')
              ? combo.useDays.split(',')
              : [combo.useDays]
          }
          if (combo.useCourse && combo.useCourse !== '') {
            this.checkedCourse = combo.useCourse.split(',')
            this.$set(this.param, 'rulesCourseFlag', '0')
          } else {
            this.$set(this.param, 'rulesCourseFlag', '1')
            this.checkedCourse = []
          }
          if (combo.useTeacherLevel && combo.useTeacherLevel !== '') {
            this.$set(this.param, 'rulesTeacherFlag', '0')
            this.checkedTeacher = combo.useTeacherLevel.split(',')
          } else {
            this.$set(this.param, 'rulesTeacherFlag', '1')
            this.checkedTeacher = []
          }
          if (combo.discountType === '1') {
            for (const item of res[1].recordList) {
              if (item.status === '1') {
                this.param.vipTypes.push({ name: item.cardName, id: item.id, value: combo.discount[item.id] * 10 || '' })
              }
            }
          } else {
            for (const item of res[1].recordList) {
              if (item.status === '1') {
                this.param.vipTypes.push({ name: item.cardName, id: item.id, value: null })
              }
            }
          }
          console.log('viplist', this.param.vipTypes)
          console.log('combo.discount', combo.discount)
          console.log('param', this.param)
          this.$refs.form.clearValidate()
          this.initCourseConfig()
          this.resetVenueProject()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleChange(value) {
      console.log('value')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.separate {
  width: 100%;
  height: 1px;
  margin: 20px 0px;
  background-color: #dfe2e8;
}
.tip {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.device-uploader {
  width: 115px;
  height: 66px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.count-style {
  display: inline-block;
  width: 45%;
  height: 60px;
}

.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 50px;
}

.clock {
  display: inline-block;
}

.upload-style {
  vertical-align: middle;
  display: inline-block;
  // width: 60px;
  // height: 60px;
  border: none;
}

.img-style {
  margin: auto;
  background-color: #eee;
  width: 100px;
  height: 60px;
  vertical-align: middle;
}

.avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.line-style {
  background-color: #dfe2e8;
  height: 1px;
  // width: 80%;
  // margin: 0 auto;
  margin-bottom: 20px;
}
</style>
